#include <stdio.h>
#include "M45PE40_SPI_Flash.h"

void M45PE40_SPI_FLASH_Init(void)
{
	SPI_InitTypeDef SPI_InitStructure;
	
	GPIO_PinRemapConfig(GPIOB, GPIO_Pin_2 | GPIO_Pin_4 | GPIO_Pin_5, GPIO_Remap_0);
	
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
	
	SPI_InitStructure.SPI_NSS = SPI_NSS_0;
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
	SPI_InitStructure.SPI_RXFIFOFullThreshold = SPI_RXFIFOFullThreshold_1;
	SPI_InitStructure.SPI_TXFIFOEmptyThreshold = SPI_TXFIFOEmptyThreshold_0;
	
	SPI_Init(SPI_FLASH_SPI, &SPI_InitStructure);
	SPI_Cmd(SPI_FLASH_SPI, ENABLE);
}

uint8_t M45PE40_SPI_FLASH_SendBytes(uint8_t byte)
{
	while (RESET == SPI_GetFlagStatus(SPI_FLASH_SPI, SPI_FLAG_TXE));
	SPI_SendData(SPI_FLASH_SPI, byte);
	
	while (RESET == SPI_GetFlagStatus(SPI_FLASH_SPI, SPI_FLAG_RXNE));
	return SPI_ReceiveData(SPI_FLASH_SPI);
}

uint32_t M45PE40_SPI_FLASH_ReadID(void)
{
	uint32_t temp = 0, temp0 = 0, temp1 = 0, temp2 = 0;
	
	M45PE40_SPI_FLASH_CS_LOW();
		
	// Send "READ IDENTIFICATION" instruction
	M45PE40_SPI_FLASH_SendBytes(M45PE40_IDENTIFICATION);
	
	temp0 = M45PE40_SPI_FLASH_SendBytes(Dummy_Byte);
	temp1 = M45PE40_SPI_FLASH_SendBytes(Dummy_Byte);
	temp2 = M45PE40_SPI_FLASH_SendBytes(Dummy_Byte);
	
	M45PE40_SPI_FLASH_CS_HIGH();
	
	temp = (temp0 << 16) | (temp1 << 8) | temp2;
	
	return temp;	
}
